<?php
namespace service;

define('ROOT_PATH', __DIR__ . DIRECTORY_SEPARATOR);

require ROOT_PATH . 'File.php';
require ROOT_PATH . 'MiandanUtil.php';
require ROOT_PATH . 'HttpUpload.php';

use service\File;
use service\HttpUpload;
use service\MiandanUtil;
use service\File2Array;



$content_type = isset($_POST['content_type'])? trim( $_POST['content_type']) : '';


if($_FILES){
    $content_type = 'file';
    // $http_upload = new HttpUpload();

    // $files = $http_upload->upload();
    // if(isset($files['csv'])){
    //     $csv = $files['csv'];
    //     echo $csv->getExtension().PHP_EOL;
    //     echo $csv->getFilename().PHP_EOL;
    //     echo $csv->getBasename().PHP_EOL;
    // }
    // var_dump($files ,$http_upload->getError());
// $uploaded = (new HttpUpload())->file();

// var_dump($uploaded);
}

function getParam($key, $default = null)
{
  return is_string($key) && isset($_REQUEST[$key]) ? $_REQUEST[$key] : $default;
}

function getRangeParams()
{
    return [
        'start' => getParam('start'),
        'end' => getParam('end'),
    ];
}

switch ($content_type) {
    case 'range':
        $data = MiandanUtil::createMdNo(...array_values(getRangeParams()));
        break;
    case 'text':
        $data = MiandanUtil::strToArray(getParam('md'));
        break;
    case 'file':
        $http_upload = new HttpUpload();
        if($files = $http_upload->upload('csv', ROOT_PATH.'uploads')){
            $file = current($files);
            $data = MiandanUtil::csvFileToArray($file);
        }
        break;
}


if($data = MiandanUtil::buildInsertData($data, MiandanUtil::buildBaseSqlData()) and is_array($data)){
    $data = MiandanUtil::arrayToInsertSql($data, 'md_table', 'INSERT IGNORE ');
}
var_dump($data);
